<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test simple webSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<input type="checkbox" id="type" checked/>是否文本
<br/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断浏览器是否支持websocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/simpleWebSocket");

        websocket.onopen = function (event) {
            setMessageInnerHTML("WebSocket连接成功");
            console.log(event);
        };

        websocket.onerror = function (event) {
            setMessageInnerHTML("WebSocket连接出错");
            console.log(event);
        };

        websocket.onmessage = function (event) {
            setMessageInnerHTML("来自服务端的消息：" + event.data);
            console.log(event);
        };

        websocket.onclose = function (event) {
            setMessageInnerHTML("WebSocket连接关闭");
            console.log(event);
        };

    } else {
        alert("当前浏览器不支持WebSocket")
    }
    function setMessageInnerHTML(message) {
        document.getElementById("message").innerHTML += message + "<br/>";
    }
    function send() {
        var message = document.getElementById('text').value;
        if (document.getElementById('type').checked) {
            websocket.send(message);
        } else {
            websocket.send(new Blob([message], {
                type: 'text/plain'
            }));
        }
    }
    function closeWebSocket() {
        websocket.close();
    }
    window.onunload = closeWebSocket;

    function blob2Str(message, charset) {
        var reader = new FileReader();
        if (!charset) charset = 'utf-8';
        reader.readAsText(message, charset);
        reader.onload = function (e) {

        }
    }
</script>

</html>